#include "doubleLoopList.h"
void initDLink(DoubleLoopLink *header) {
    header->next = header;
    header->prev = header;
    header->val = 0;
}

/* 插入的工具接口
 * new_node : 新节点的地址
 * prev : 新节点的前一个节点
 * next : 新节点的后一个节点
 * */
static void addDNode(DoubleNode *new_node, DoubleNode *prev, DoubleNode *next) {
    next->prev = new_node;
    new_node->next = next;
    new_node->prev = prev;
    prev->next = new_node;
}
/* 删除的工具接口
 * prev : 删除这个节点的前一个位置
 * next : 删除这个节点的后一个位置
 * */
static void delDNode(DoubleNode *prev, DoubleNode *next) {
    prev->next = next;
    next->prev = prev;
}

void insertDLinkHeader(DoubleLoopLink *header, Element val) {
    DoubleNode *new_node = (DoubleNode *) malloc(sizeof(DoubleNode));
    new_node->val = val;
    addDNode(new_node, header, header->next);
    ++header->val;
}

void insertDLinkRear(DoubleLoopLink *header, Element val) {
    DoubleNode *new_node = (DoubleNode *) malloc(sizeof(DoubleNode));
    new_node->val = val;
    addDNode(new_node, header->prev, header);
    ++header->val;
}

void showDLink(DoubleLoopLink *header) {
    DoubleNode *node;
    printf("show:  ");
    for (node = header->next; node != header; node = node->next) {
        printf("%d\t", node->val);
    }
    printf("\n");
}

void deleteDLink(DoubleLoopLink *header, Element e) {
    // 1. 找到这个元素，可以就地删除，不需要找前置节点
    DoubleNode *node;
    for (node = header->next; node != header; node = node->next) {
        if (node->val == e) {
            break;
        }
    }
    // 2. 判断是否找到
    if (node != header) {		// 找到
        delDNode(node->prev, node->next);
        free(node);
        --header->val;
    } else {
        printf("Not find %d element!\n", e);
    }
}

void releaseDLink(DoubleLoopLink *header) {
    DoubleNode *node, *tmp;
    for (node = header->next; node != header;) {
        tmp = node;
        delDNode(node->prev, node->next);
        node = node->next;
        free(tmp);
        --header->val;
    }
}
